import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class MF_bookfind_manager_findbookbystoragetime extends JFrame {
    private JTextField searchField;
    private JButton searchButton;
    private JTable table;
    private DefaultTableModel tableModel;


    public MF_bookfind_manager_findbookbystoragetime() {
        setTitle("Book Management");
        setSize(800, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        searchField = new JTextField(20);
        searchButton = new JButton("查询");

        JPanel searchPanel = new JPanel();
        searchPanel.add(new JLabel("请输入入库时间:"));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);

        String[] columnNames = {"ID", "书名", "作者", "存储时间", "数量", "位置"};
        tableModel = new DefaultTableModel(columnNames, 0);
        table = new JTable(tableModel);

        add(searchPanel, BorderLayout.NORTH);
        add(new JScrollPane(table), BorderLayout.CENTER);

        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                searchBook();
            }
        });
    }

    private void searchBook() {
        String book_title = searchField.getText().trim();
        if (book_title.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入入库时间");
            return;
        }

        String query = "SELECT * FROM book_information WHERE storage_time = ?";
        try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javaproject", "root", "root");
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setString(1, book_title);
            ResultSet rs = stmt.executeQuery();

            boolean found = false;
            tableModel.setRowCount(0); // 清空表格
            while (rs.next()) {
                found = true;
                Object[] row = {
                        rs.getString("book_id"),
                        rs.getString("book_title"),
                        rs.getString("writer"),
                        rs.getString("storage_time"),
                        rs.getString("number"),
                        rs.getString("position")
                };
                tableModel.addRow(row);
            }
            if (!found) {
                JOptionPane.showMessageDialog(this,"请以yyyy-MM-dd时间格式查询");
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "数据库查询失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new MF_bookfind_manager_findbookbystoragetime().setVisible(true));
    }
}